import { defineStore } from 'pinia'
import md5 from 'js-md5'
import api_user from '@/api/user.js'
import defAva from '@/static/logo.png'

export const useUserStore = defineStore('user', {
	state: () => {
		return {
			token: uni.getStorageSync('token'),
			id: '',
			name: '',
			nickName: '',
			avatar: '',
			tenantId: null,
			roles: [],
			permissions: []
		}
	},
	actions: {
		login(userInfo) {
			const username = userInfo.username.trim()
			const password = md5(userInfo.password)
			return new Promise((resolve, reject) => {
				api_user.login({ username, password })
					.then(res => {
						const data = res.data
						uni.setStorageSync('token', data.access_token)
						this.token = data.access_token
						resolve()
					})
					.catch(reject)
			})
		},
		getInfo() {
			return new Promise((resolve, reject) => {
				api_user.getInfo()
					.then(res => {
						const user = res.user
						const avatar = user.avatar == '' || user.avatar == null ? defAva : user.avatar

						if (res.roles && res.roles.length > 0) {
						  this.roles = res.roles
						  this.permissions = res.permissions
						} else {
						  this.roles = ['ROLE_DEFAULT']
						}
						this.id = user.userId
						this.name = user.userName
						this.tenantId = user.tenantId
						this.nickName = user.nickName
						this.avatar = avatar
						resolve()
					})
					.catch(reject)
			})
		},
		logOut() {
			return new Promise((resolve, reject) => {
				api_user.logout()
					.then(() => {
						this.removeInfo()
						resolve()
					})
					.catch(reject)
			})
		},
		removeInfo() {
			this.token = ''
			this.roles = []
			this.permissions = []
			uni.removeStorageSync('token')
		}
	}
})